package com.hi3v.auth.monitor;

import com.hi3v.auth.monitor.auth.ExampleAuthenticator;
import com.hi3v.auth.monitor.auth.ExampleAuthorizer;
import com.hi3v.auth.monitor.core.Template;
import com.hi3v.auth.monitor.core.User;
import com.hi3v.auth.monitor.db.LoginRecordDAO;
import com.hi3v.auth.monitor.db.PersonDAO;
import com.hi3v.auth.monitor.filter.DateRequiredFeature;
import com.hi3v.auth.monitor.health.TemplateHealthCheck;
import com.hi3v.auth.monitor.resources.*;
import com.hi3v.auth.monitor.tasks.EchoTask;
import io.dropwizard.Application;
import io.dropwizard.auth.AuthDynamicFeature;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.auth.basic.BasicCredentialAuthFilter;
import io.dropwizard.jdbi3.JdbiFactory;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.jdbi.v3.core.Jdbi;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import java.util.EnumSet;

public class AuthMonitorApplication extends Application<AuthMonitorConfiguration> {
    public static void main(String[] args) throws Exception {
        new AuthMonitorApplication().run(args);
    }


    @Override
    public String getName() {
        return "auth-monitor";
    }

    @Override
    public void run(AuthMonitorConfiguration configuration, Environment environment) {
        final JdbiFactory factory = new JdbiFactory();
        final Jdbi jdbi = factory.build(environment, configuration.getDataSourceFactory(), "mysql");
        final PersonDAO dao = jdbi.onDemand(PersonDAO.class);
        final LoginRecordDAO loginRecordDAO = jdbi.onDemand(LoginRecordDAO.class);

        environment.jersey().register(new PeopleResource(dao));
        environment.jersey().register(new MonitorResource(loginRecordDAO));

        final Template template = configuration.buildTemplate();

        environment.healthChecks().register("template", new TemplateHealthCheck(template));
        environment.admin().addTask(new EchoTask());
        environment.jersey().register(DateRequiredFeature.class);
        environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>()
                .setAuthenticator(new ExampleAuthenticator())
                .setAuthorizer(new ExampleAuthorizer())
                .setRealm("SUPER SECRET STUFF")
                .buildAuthFilter()));
        environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
        environment.jersey().register(RolesAllowedDynamicFeature.class);
        environment.jersey().register(new HelloWorldResource(template));
        environment.jersey().register(new ViewResource());
        environment.jersey().register(new ProtectedResource());
        environment.jersey().register(new FilteredResource());


    }
}
